<template>
  <!-- 分类参数 -->
  <div class="params-container">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        show-icon
        type="warning"
        :closable="false"
      >
      </el-alert>

      <!-- 选择分类区域 -->
      <el-row style="margin: 15px 0;">
        <el-col>
          <label>选择商品分类：</label>
          <!-- cascader
               change-on-select
               clearable:是否支持清空选项
               options:可选项数据源(是一个对象)，键名可通过 Props 属性配置
               props:配置选项 
               @change:当选中节点变化时触发
           -->
          <el-cascader
            clearable
            ref="cascaderRef"
            style="width: 30%"
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parendCateChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- Tabs 标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <!-- 动态参数标签页区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table
            border
            stripe
            size="mini"
            :data="manyTabData"
            style="width: 100%"
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-tag
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleClose(scope.row, index)"
                    >{{ item }}</el-tag
                  >
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    ref="saveTagBtn"
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </el-row>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数标签页区域 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table
            border
            stripe
            size="mini"
            :data="onlyabData"
            style="width: 100%"
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-tag
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                    @close="handleClose(scope.row, index)"
                    >{{ item }}</el-tag
                  >
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    ref="saveTagBtn"
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </el-row>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框区域 -->
    <el-dialog
      width="40%"
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="formRules"
        label-width="90px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input
            v-model="addForm.attr_name"
            :placeholder="'请输入' + titleText"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPararms">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框区域 -->
    <el-dialog
      width="40%"
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="90px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input
            v-model="editForm.attr_name"
            :placeholder="'请输入' + titleText"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePararms">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        // 次级菜单的展开方式
        expandTrigger: 'click',
        // 是否严格的遵守父子节点不互相关联(可以选择任意一级)
        checkStrictly: false
      },
      selectedKeys: [],
      // 默认显示的 tab 标签页名字
      activeName: 'many',
      // 动态参数数据
      manyTabData: [],
      // 静态参数数据
      onlyabData: [],
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      formRules: {
        attr_name: [
          { required: true, message: '请填写该参数', trigger: 'blur' }
        ]
      },
      editForm: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // 判断数据获取是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 获取表格数据的请求方法
    async getParamsData() {
      if (!this.cateId) return
      // 发送获取数据的请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200)
        return this.$message.error('获取参数列表失败')

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制按钮与文本框的切换显示
        item.inputVisible = false
        // 文本框双向绑定的值
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyabData = res.data
      }
    },
    // 级联选择器选择项发生改变时触发函数
    parendCateChange() {
      // 如果选中的节点不是三级，则清空数组
      if (this.selectedKeys.length !== 3) {
        // 清空数据
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyabData = []
      }
      // 隐藏级联选择器的下拉选择列表
      this.$refs.cascaderRef.dropDownVisible = false
      this.getParamsData()
    },
    // tab 标签页的点击触发函数
    tabsClick() {
      // 重新获取数据
      this.getParamsData()
    },
    // 添加对话框关闭时触发
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数处理函数
    addPararms() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('保存失败！')
        this.$message.success('添加成功！')
        this.getParamsData()
        this.addDialogVisible = false
      })
    },
    // 显示修改对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200)
        return this.$message.error('获取参数信息错误！')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改信息时触发的函数
    savePararms() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败！')
        this.$message.success('修改成功！')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 修改对话框关闭时触发
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.editForm = {}
    },
    // 根据 id 删除对应的参数
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户确认删除，则返回字符串 confirm
      // 如果用户取消删除，则返回字符串 cancel
      if (confirmResult === 'cancel') return
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      this.getParamsData()
    },
    // 显示参数可选项的文本框
    showInput(row) {
      row.inputVisible = true
      // this.$nextTick:方法的作用：当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 将 attr_vals 数组的操作保存到数据库方法
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200)
        return this.$message.error('修改参数可选项失败！')
      this.$message.success('修改参数可选项成功!')
      row = res.data
    },
    // input-new-tag 的回车和失去焦点时调用函数
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      // 保存数据
      this.saveAttrVals(row)
    },
    // 删除对应的参数可选项
    async handleClose(row, index) {
      //   const confirmResult = await this.$confirm(
      //     '此操作将永久删除该数据, 是否继续?',
      //     '提示',
      //     {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning'
      //     }
      //   ).catch(err => err)
      //   // 如果用户确认删除，则返回字符串 confirm
      //   // 如果用户取消删除，则返回字符串 cancel
      //   if (confirmResult === 'cancel') return

      row.attr_vals.splice(index, 1)

      // 保存数据
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 控制添加按钮的启用和禁用状态
    isBtnDisabled() {
      return this.selectedKeys.length === 0 ? true : false
    },
    // 当前选中的三级分类的 id
    cateId() {
      return this.selectedKeys.length > 2
        ? this.selectedKeys[this.selectedKeys.length - 1]
        : null
    },
    // 对话框标题文本
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态参数'
    }
  },
  watch: {}
}
</script>

<style lang="less" scoped>
.params-container {
  //   height: 100%;
  max-height: 99%;
  overflow: hidden;

  .el-tag + .el-tag {
    margin-top: 5px;
    margin-left: 10px;
  }
  .button-new-tag {
    margin-top: 10px;
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
</style>
